<template>
   <div class="row">
    <h1 v-if=isFirst>欢迎进入此网站...</h1>
    <h1 v-else-if="isLoading">资源正在加载 请勿着急...</h1>
    <h1 v-else-if="isError">{{isError}}</h1>
    <div v-else class="card" v-for="card in cards" :key="card.id">
      <a :href="card.url" target="_blank">
        <img :src="card.avatar_url" style='width: 100px'/>
      </a>
      <p class="card-text">{{card.login}}</p>
    </div>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: 'Main',
  data(){
    return {
      isFirst:true,
      isLoading:false,
      isError:'',
      cards:[],
    }
  },
  // 在挂载阶段，发送请求
  mounted(){
    this.$bus.$on('getKeyword',(keyword)=>{
      // 在发送请求前修改isFirst和isLoading
      this.isFirst = false,
      this.isLoading = true,

      // 根据接收到的keyword发送axios请求
      axios({
        url:'https://api.github.com/search/users?',
        params:{
          q:keyword,
        },
        method:'get',
      })
      .then((res)=>{
        // 发送请求成功
        // console.log(res.data);
        // 修改isLoading
        this.isLoading = false,

        this.cards = res.data.items.map(item=>{
          return {
            id:item.id,
            login:item.login,
            url:item.url,
            avatar_url:item.avatar_url
          }
        })
        // console.log(this.cards);
      },(err)=>{
        // 发送请求失败
        this.isLoading = false,
        this.isError = err.message
      })
    })

   
  },

}
</script>

<style scoped>
  .card {
  float: left;
  width: 33.333%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: .75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>
